package com.relytosoft.mizar.media.common.config;

import feign.Feign;
import feign.codec.Encoder;
import feign.form.FormEncoder;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.X509TrustManager;
import java.util.concurrent.TimeUnit;

/**
 * OpenFeign的OkHttp3配置
 *
 * @author Jierry
 * @version 2022/4/2.
 */
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignConfig {

    @Bean
    public Encoder encoder() {
        return new FormEncoder();
    }

    @Bean
    public OkHttpClient.Builder okHttpClientBuilder() {
        X509TrustManager manager = SSLSocketClient.getX509TrustManager();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(SSLSocketClient.getSocketFactory(manager), manager);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool());
        return builder;
    }
}

